<template>
	<!-- 此处改动，camear文件为新添加文件  -->
	<view class="live-camera">
		<view class="preview">

			<camera v-if='cameraHeight!=="" && isShowCamera' device-position="front" flash="off"
				:style="{ width: cameraWidth+'px', height: cameraHeight+'px' }">
			</camera>
			<!--提示语-->
			<view class="remind">
				<text class="remind-text" style="">{{ message }}</text>
			</view>

			<!--辅助线-->
			<view class="outline-box">
				<image class="outline-img" src="http://images.linglinggong.net/live-camera/outline/1.png" style="">
				</image>
			</view>
		</view>

		<view class="menu">

			<!--返回键-->
			<image class="menu-back" @tap="back" src="http://images.linglinggong.net/userifo-supplement/fanhui.png">
			</image>

			<!--快门键-->
			<image class="menu-snapshot" @tap="snapshot"
				src="http://images.linglinggong.net/userifo-supplement/click-shot.png"></image>

			<!--相册键-->
			<view class="menu-flip" @click="album">相册</view>
		</view>
		<!-- 辅助裁剪的canvas，不显示给用户，因为720太大，界面放不下 -->
		<canvas canvas-id='image-canvas'
			style='width:750px;height:750px;position:fixed;top:-10000px;left:-10000px;'></canvas>
	</view>
</template>

<script>
	var listener
	export default {
		data() {
			return {
				dotype: 'idphoto', //操作类型
				message: '', //提示
				aspect: '2:3', //比例
				cameraWidth: '', //相机画面宽度
				cameraHeight: '', //相机画面宽度
				windowWidth: '', //屏幕可用宽度
				windowHeight: '', //屏幕可用高度
				camerastate: false, //相机准备好了
				livePusher: null, //流视频对象
				snapshotsrc: null, //快照
				image: "",
				uploadToken: '', //七牛上传TOKEN
				isShowCamera: false,
				ctx: ''
			};
		},
		onLoad(e) {
			if (e.dotype != undefined) this.dotype = e.dotype;
			this.getSetting()
		},
		beforeMount() {
			this.initCamera();
		},
		methods: {
			/* 判断用户是否授权相机 */
			// 判断用户是否授权
			getSetting() {
				uni.getSetting({
					success: (res) => {
						if (res.authSetting['scope.camera'] != undefined && res.authSetting[
								'scope.camera'] != true) { //非初始化进入该页面,且未授权
							uni.showModal({
								title: '是否授权相机权限',
								content: '需要获取您的相机权限，请确认授权，否则无法为您拍摄头像',
								success: res => {
									if (res.cancel) {
										uni.showToast({
											title: '授权失败',
											icon: 'none',
											duration: 1000
										})
									} else if (res.confirm) {
										this.openSet()
									}
								}
							})
						} else {
							this.isShowCamera = true
							// #ifndef MP-TOUTIAO
							this.ctx = uni.createCameraContext()
							// #endif
							// #ifdef MP-TOUTIAO
							this.ctx = tt.createCameraContext()
							// #endif
						}
					}
				})
			},
			/* 打开设置 */
			openSet() {
				uni.openSetting({
					success: dataAu => {
						if (dataAu.authSetting[
								"scope.camera"] ==
							true) {
							uni.showToast({
								title: '授权成功',
								icon: 'success',
								duration: 1000
							})
							this.isShowCamera = true
							// #ifndef MP-TOUTIAO
							this.ctx = uni.createCameraContext()
							// #endif
							// #ifdef MP-TOUTIAO
							this.ctx = tt.createCameraContext()
							// #endif
						} else {
							uni.showToast({
								title: '授权失败',
								icon: 'none',
								duration: 1000
							})
						}
					}
				})
			},
			//初始化相机
			initCamera() {
				uni.getSystemInfo({
					success: res => {
						this.windowWidth = res.windowWidth;
						this.windowHeight = res.windowHeight;
						this.cameraWidth = res.windowWidth;
						this.cameraHeight = res.windowWidth * 1.5;
					}
				});
			},
			//返回
			back() {
				uni.navigateBack();
			},

			//抓拍
			snapshot() {
				uni.getSetting({
					success: (res) => {
						if (res.authSetting['scope.camera'] != undefined && res.authSetting[
								'scope.camera'] != true) {
							uni.showToast({
								title: "请授权相机后重新进入", // 内容
								success: (res) => {
									this.openSet()
								},
							});
						} else {
							// #ifndef MP-TOUTIAO
							this.ctx.takePhoto({
								quality: 'high', //拍摄质量(high:高质量 normal:普通质量 low:高质量)
								success: (res) => {
									var file = res.tempImagePath;
									this.makeimageOK(file)
								},
								fail: (res) => {
									//拍摄失败
								},
							})
							// #endif
							// #ifdef MP-TOUTIAO
							console.log(this.ctx)
							this.startOnFrame()
							setTimeout(() => {
								this.stopOnFrame()
							}, 500)
							// #endif
						}
					},
					fail: (err) => {
						uni.showModal({
							title: "获取授权失败",
							content: JSON.stringify(err),
						});
					},
				});
				//拍摄照片

			},
			startOnFrame(e) {
				listener = this.ctx.onCameraFrame((frame) => {
					let {
						width,
						height,
						data
					} = frame;
					console.log('开启监听', frame)

				});

				listener.start({
					success: (res) => {
						console.log('开始接收的帧参数', res)
						tt.showToast({
							title: "开始接收帧数据"
						});
					},
					fail: (err) => {
						tt.showModal({
							title: "接收失败",
							content: JSON.stringify(err),
						});
					},
				});
			},
			stopOnFrame() {
				listener.stop({
					success: (res) => {
						console.log('结束接收的帧参数', res)
						tt.showToast({
							title: "停止接收帧数据"
						});
					},
					fail: (err) => {
						tt.showModal({
							title: "停止接收出错",
							content: JSON.stringify(err),
						});
					},
				});
			},
			//判断图片是否符合规范
			makeimageOK(tempImagePath) {
				uni.getImageInfo({
					src: tempImagePath,
					success: res => {
						if (res.width == res.height) {
							uni.setStorageSync("idphoto", tempImagePath)
							const pages = getCurrentPages(); //获取页面栈
							const beforePage = pages[pages.length - 2]; //前一个页面
							beforePage.$vm.updateUserImage(tempImagePath); //前一个页面方法
							uni.navigateBack();
						} else {
							this.loadTempImagePath(tempImagePath, res.width, res.height)
						}
					},
					fail: fail => {}
				})
			},

			// 参数options是拍照获取到的临时路径
			loadTempImagePath(path, width, height) {
				// 矩形的位置 (设置了要求的大小:720)
				console.log(width, height)

				var image_x = 0;
				var image_y = 0;
				var image_width = this.windowWidth;
				var image_height = this.windowWidth;
				var img_height = (image_width / width) * height
				//过渡页面中，图片的路径坐标和大小
				var canvas = uni.createCanvasContext("image-canvas")
				canvas.drawImage(path, 0, 0, image_width, img_height)
				uni.showLoading({
					title: '数据处理中...',
					icon: 'loading',
					mask: true,
					duration: 10000
				})
				canvas.strokeStyle = '#f4f8f9';
				// canvas.strokeRect(image_x, image_y, image_width, image_height)
				canvas.draw(
					true, () => {
						uni.canvasToTempFilePath({
							canvasId: "image-canvas",
							x: image_x, //画布x轴起点
							y: image_y, //画布y轴起点
							width: image_width, //画布宽度
							height: image_height*1.3, //画布高度
							destWidth: image_width, //输出图片宽度
							destHeight: image_height*1.3, //输出图片高度
							success: res => {
								uni.hideLoading()
								const pages = getCurrentPages(); //获取页面栈
								const beforePage = pages[pages.length - 2]; //前一个页面
								beforePage.$vm.updateUserImage(res.tempFilePath); //前一个页面方法
								uni.navigateBack();
								uni.getImageInfo({
									src: res.tempFilePath,
									success: res => {
										console.log('111111111111',res)
									},
									fail: fail => {}
								})
							},
							fail: e => {
								uni.hideLoading()
								uni.showToast({
									title: '出错啦...',
									icon: 'loading'
								})
							}
						})
					}
				)
			},
			// 调用本地相册
			album() {
				uni.chooseImage({
					count: 1, //最多可以选择的图片张数
					sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: (res) => {
						if (res.tempFilePaths.length > 1) return uni.showToast({
							title: '最多上传1张图片',
							icon: 'none'
						})

						// console.log(res,"路径");
						// 将路径存到本地
						uni.navigateBack({
							delta: 1
						})
						console.log("1233344", res.tempFiles[0].path)
						const pages = getCurrentPages(); //获取页面栈
						const beforePage = pages[pages.length - 2]; //前一个页面
						beforePage.$vm.updateUserImage(res.tempFiles[0].path); //前一个页面方法
					}
				})
			},

		}
	};
</script>

<style lang="scss" scoped>
	.live-camera {
		.preview {
			justify-content: center;
			align-items: center;

			.outline-box {
				position: absolute;
				top: 0;
				left: 0;
				z-index: 99;
				align-items: center;
				justify-content: center;

				.outline-img {
					width: 750rpx;
					height: 1125rpx;
				}
			}

			.remind {
				position: absolute;
				top: 880rpx;
				width: 750rpx;
				z-index: 100;
				align-items: center;
				justify-content: center;

				.remind-text {
					color: #dddddd;
					font-weight: bold;
				}
			}
		}

		.menu {
			background-color: #fff;
			position: absolute;
			left: 0;
			bottom: 0rpx;
			width: 100vw;
			height: 350rpx;
			z-index: 100;
			display: flex;
			justify-content: center;
			align-items: center;

			.menu-back {
				width: 80rpx;
				height: 80rpx;
				align-items: center;
				justify-content: center;
				margin-right: 150rpx;
			}

			.menu-snapshot {
				width: 130rpx;
				height: 130rpx;
			}

			.menu-flip {
				width: 80rpx;
				height: 80rpx;
				text-align: center;
				font-size: 30rpx;
				font-weight: bold;
				line-height: 80rpx;
				margin-left: 150rpx;
			}
		}
	}
</style>
